package com.lancoo.znbkxx.uis;


import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;

import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.githang.statusbar.StatusBarCompat;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lancoo.znbkxx.R;
import com.lancoo.znbkxx.adapter.EditImageAdapter;
import com.lancoo.znbkxx.base.AppApplication;
import com.lancoo.znbkxx.base.BaseActivity;
import com.lancoo.znbkxx.beans.EditSaveBean;
import com.lancoo.znbkxx.beans.ImagePostBean;
import com.lancoo.znbkxx.beans.MyNoteList;
import com.lancoo.znbkxx.net.MyNoteEditApi;
import com.lancoo.znbkxx.net.OnSuccessAndFaultListener;
import com.lancoo.znbkxx.net.OnSuccessAndFaultSub;
import com.lancoo.znbkxx.views.DrawingBoardView;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Create by TangJun on 2019/2/16
 */
public class MyNoteEditActivity extends BaseActivity implements View.OnClickListener{
    /* 头像文件 */
    private static final String IMAGE_FILE_NAME = "temp_head_image.jpg";
    private static final String CROP_IMAGE_FILE_NAME = "bala_crop.jpg";
    /* 请求识别码 */
    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;

    // 裁剪后图片的宽(X)和高(Y),480 X 480的正方形。
    private static int output_X = 480;
    private static int output_Y = 480;
    //改变头像的标记位
    private int new_icon=0xa3;
    private ImageView headImage = null;
    private String mExtStorDir;
    private Uri mUriPath;
    private File mFile = null;
    private List<File> fileList = new ArrayList<>();

    private final int PERMISSION_READ_AND_CAMERA =0;//读和相机权限
    private final int PERMISSION_READ =1;//读取权限
    private int num = 0;
    public static final String INTENT_CONTENT = "content";
    public static final String INTENT_NAME = "name";
    public static final String INTENT_PATH = "path";
    private EditText tvContent;
    private ImageView ivAdd1;
    private ImageView ivDelete1;
    private ImageView ivAdd2;
    private ImageView ivDelete2;
    private RecyclerView recyclerView;
    private ImageView ivBack;
    private ImageView ivEdit;
    private ImageView ivTrash;
    private ImageView ivSave;
    private ImageView ivSave1;
    private ImageView ivCancel;
    private TextView tvName;
    private View mPopView;
    private View mDoodlingView;
    private RelativeLayout rlRoot;
    private PopupWindow mPopupWindow;
    private PopupWindow mDoodlingWindow;
    private TextView tvFromAlbum;
    private TextView tvPhotograph;
    private TextView tvDoodling;
    private TextView tvCancel;
    private TextView doodlingComplete;
    private TextView doodlingCancel;
    private DrawingBoardView drawingBoardView;
    private List<String> pathList;
    private List<String> imagePathList = new ArrayList<>();
    ;
    private EditImageAdapter adapter;
    private ImageView ivDelete;
    private ImageView ivAdd;
    public static Intent getInstance(String content, String name, String path) {
        Intent intent = new Intent(AppApplication.getInstance(), MyNoteEditActivity.class);
        intent.putExtra(INTENT_CONTENT,content);
        intent.putExtra(INTENT_NAME,name);
        intent.putExtra(INTENT_PATH,path);
        return intent;
    }
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_note_edit);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.color_2884EC));
        mExtStorDir = Environment.getExternalStorageDirectory().toString();
        initPopWindow();
        initDoodlingWindow();
        findViews();
        getDate();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {

        // 用户没有进行有效的设置操作，返回
        if (resultCode == RESULT_CANCELED) {
            //  Toast.makeText(getApplication(), "取消", Toast.LENGTH_LONG).show();
            return;
        }

        switch (requestCode) {
            case CODE_GALLERY_REQUEST:
                cropRawPhoto(intent.getData());
                break;

            case CODE_CAMERA_REQUEST:
                if (hasSdcard()) {
                    File tempFile = new File(
                            Environment.getExternalStorageDirectory(),
                            IMAGE_FILE_NAME);
                    //                    cropRawPhoto(Uri.fromFile(tempFile));
                    //adapter.addNewItem(getImageContentUri(tempFile).getPath());
                    cropRawPhoto(getImageContentUri(tempFile));
                } else {
                    Toast.makeText(getApplication(), "没有SDCard!", Toast.LENGTH_LONG)
                            .show();
                }

                break;

            case CODE_RESULT_REQUEST:
                try {
                  /*  Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(mUriPath));
                    setImageToHeadView(intent,bitmap);
                    Log.i("tj","file://" + mFile.getAbsolutePath());*/
                    //adapter.addNewItem("file://"+ mFile.getAbsolutePath());
                    upLoad2Server(mFile);
                    mPopupWindow.dismiss();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
        }

        super.onActivityResult(requestCode, resultCode, intent);
    }
    private void setImageToHeadView(Intent intent,Bitmap b) {
        try {
            if (intent != null) {
                /*if (num == 1){
                    ivAdd1.setImageBitmap(b);
                    ivDelete1.setVisibility(View.VISIBLE);
                    mPopupWindow.dismiss();
                }else if (num == 2){
                    ivAdd2.setImageBitmap(b);
                    ivDelete2.setVisibility(View.VISIBLE);
                    mPopupWindow.dismiss();
                }
                num = 0;*/
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void cropRawPhoto(Uri uri) {

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");

        // 设置裁剪
       /* intent.putExtra("crop", "true");

        // aspectX , aspectY :宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
*/
        // outputX , outputY : 裁剪图片宽高
        intent.putExtra("outputX", output_X);
        intent.putExtra("outputY", output_Y);
        intent.putExtra("return-data", true);

        //startActivityForResult(intent, CODE_RESULT_REQUEST); //直接调用此代码在小米手机有异常，换以下代码
        String mLinshi = System.currentTimeMillis() + CROP_IMAGE_FILE_NAME;
        mFile = new File(mExtStorDir, mLinshi);
        //        mHeadCachePath = mHeadCacheFile.getAbsolutePath();

        mUriPath = Uri.parse("file://"+ mFile.getAbsolutePath());
        //upLoad2Server(new File("file://"+ mFile.getAbsolutePath()));
        //将裁剪好的图输出到所建文件中
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mUriPath);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        //注意：此处应设置return-data为false，如果设置为true，是直接返回bitmap格式的数据，耗费内存。设置为false，然后，设置裁剪完之后保存的路径，即：intent.putExtra(MediaStore.EXTRA_OUTPUT, uriPath);
        //        intent.putExtra("return-data", true);
        intent.putExtra("return-data", false);
        //        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivityForResult(intent, CODE_RESULT_REQUEST);
    }
    public Uri getImageContentUri(File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Images.Media._ID },
                MediaStore.Images.Media.DATA + "=? ",
                new String[] { filePath }, null);

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }
    private void initDoodlingWindow(){
        mDoodlingView = getLayoutInflater().inflate(R.layout.view_doodling,null);
        mDoodlingWindow = new PopupWindow(mDoodlingView,
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        mDoodlingWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow()
                        .getAttributes();
                lp.alpha = 1f;
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                getWindow().setAttributes(lp);

            }
        });
    }
    private void initPopWindow() {
        mPopView = getLayoutInflater().inflate(R.layout.view_note_edit, null);
        // 将转换的View放置到 新建一个popuwindow对象中
        mPopupWindow = new PopupWindow(mPopView,
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        // 点击popuwindow外让其消失
        mPopupWindow.setOutsideTouchable(true);
        //获取焦点
        mPopupWindow.setFocusable(true);
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow()
                        .getAttributes();
                lp.alpha = 1f;
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                getWindow().setAttributes(lp);

            }


        });

    }
    private void getDate() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OnSuccessAndFaultListener l = new OnSuccessAndFaultListener() {
                    @Override
                    public void onSuccess(String result) {//成功回调
                        Gson gson = new Gson();
                        final MyNoteList infoBean = gson.fromJson(result,MyNoteList.class);
                        Message msg =Message.obtain();
                        msg.obj = infoBean;
                        msg.what = 1;   //标志消息的标志
                        handler.sendMessage(msg);
                    }
                    @Override
                    public void onFault(String errorMsg) {//失败的回调
                        Log.i("tj",errorMsg);
                    }
                };
                MyNoteEditApi.getMyNoteEditInfo(new OnSuccessAndFaultSub(l));


            }
        }).start();
    }
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    //imagePathList.clear();
                    ImagePostBean bean = (ImagePostBean)msg.obj;
                    Log.i("tj_path",bean.getRelativePath());
                    imagePathList.add(bean.getRelativePath());
                    adapter.addNewItem("file://"+ mFile.getAbsolutePath());
                    break;
                case 1:

                    break;
            }
        }
    };
    private void findViews(){
        tvName = findViewById(R.id.tv_name);
        tvName.setText(getIntent().getStringExtra(INTENT_NAME));
        tvContent = findViewById(R.id.tv_content);
        tvContent.setText(getIntent().getStringExtra(INTENT_CONTENT));
        tvContent.setSelection(getIntent().getStringExtra(INTENT_CONTENT).length());
        //ivAdd1 = findViewById(R.id.iv_add1);
        //ivDelete1 = findViewById(R.id.iv_delete1);
        //ivDelete1.setVisibility(View.INVISIBLE);
        //ivAdd2 = findViewById(R.id.iv_add2);
        //ivDelete2 = findViewById(R.id.iv_delete2);
        //ivDelete2.setVisibility(View.INVISIBLE);
        recyclerView = findViewById(R.id.rv_image);
        pathList = new ArrayList<>();
        String path = getIntent().getStringExtra(INTENT_PATH);
        String[] mPath = path.split("\\|");
        for (String string : mPath){
            pathList.add(string);
            Log.i("tj",string);
            imagePathList.add(string);
        }
        LinearLayoutManager gridLayoutManager = new GridLayoutManager(AppApplication.getInstance(),3);
       //linearLayoutManager.setOrientation(LinearLayout.HORIZONTAL);
        recyclerView.setLayoutManager(gridLayoutManager);
        adapter = new EditImageAdapter(imagePathList, new EditImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                showPopWindow();
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });
       /* for (int i = 0; i < recyclerView.getChildCount(); i++){
            RelativeLayout relativeLayout= (RelativeLayout) recyclerView.getChildAt(i);
            ivAdd = relativeLayout.findViewById(R.id.iv_add);
            ivDelete = relativeLayout.findViewById(R.id.iv_delete);
        }*/
       adapter.setOnDeleteClickListener(new EditImageAdapter.OnDeleteClickLister() {
           @Override
           public void onDeleteClick(View view, int position) {
               adapter.deleteItem(position);

               imagePathList.remove(position );

           }
       });
        recyclerView.setAdapter(adapter);
        ivBack = findViewById(R.id.iv_back);
        ivEdit = findViewById(R.id.iv_edit);
        ivTrash = findViewById(R.id.iv_trash);
        ivSave = findViewById(R.id.iv_save);
        ivSave1 = findViewById(R.id.iv_save_1);
        ivCancel = findViewById(R.id.iv_cancel);
        rlRoot = findViewById(R.id.rl_root);
        tvCancel = mPopView.findViewById(R.id.tv_cancel);
        tvPhotograph = mPopView.findViewById(R.id.tv_photograph);
        tvFromAlbum = mPopView.findViewById(R.id.tv_fromAlbum);
        tvDoodling = mPopView.findViewById(R.id.tv_doodling);
        doodlingComplete = mDoodlingView.findViewById(R.id.tv_complete);
        doodlingCancel = mDoodlingView.findViewById(R.id.tv_cancle);
        drawingBoardView = mDoodlingView.findViewById(R.id.view_doodling);
        tvCancel.setOnClickListener(this);
        tvPhotograph.setOnClickListener(this);
        tvFromAlbum.setOnClickListener(this);
        tvDoodling.setOnClickListener(this);
        ivCancel.setOnClickListener(this);
//        ivAdd1.setOnClickListener(this);
//        ivAdd2.setOnClickListener(this);
//        ivDelete1.setOnClickListener(this);
//        ivDelete2.setOnClickListener(this);
        ivSave1.setOnClickListener(this);
        ivSave.setOnClickListener(this);
        ivEdit.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        doodlingComplete.setOnClickListener(this);
        doodlingCancel.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_edit:
                ivTrash.setVisibility(View.INVISIBLE);
                ivEdit.setVisibility(View.INVISIBLE);
                ivSave1.setVisibility(View.VISIBLE);
                ivCancel.setVisibility(View.VISIBLE);
                adapter.updateData(1);
                break;
            case R.id.iv_save:
                ivSave.setVisibility(View.INVISIBLE);
                ivTrash.setVisibility(View.VISIBLE);
                ivEdit.setVisibility(View.VISIBLE);
                break;
            case R.id.iv_save_1:
                ivSave1.setVisibility(View.INVISIBLE);
                ivCancel.setVisibility(View.INVISIBLE);
                ivTrash.setVisibility(View.VISIBLE);
                ivEdit.setVisibility(View.VISIBLE);
                //adapter.notifyDataSetChanged();
                Log.i("tj_path",imagePathList.toString());
                adapter.updateData(0);
                postSave();
                //getImagePost(fileList);
                //upLoad2Server(mFile);
                break;
           /* case R.id.iv_add1:
                if (ivDelete1.getVisibility() == View.INVISIBLE){
                    showPopWindow();
                    num = 1;
                }
                break;
            case R.id.iv_add2:
                if (ivDelete2.getVisibility() == View.INVISIBLE){
                    showPopWindow();
                    num = 2;
                }
                break;
            case R.id.iv_delete1:
                ivAdd1.setImageResource(R.mipmap.icon_add);
                ivDelete1.setVisibility(View.INVISIBLE);
                break;
            case R.id.iv_delete2:
                ivAdd2.setImageResource(R.mipmap.icon_add);
                ivDelete2.setVisibility(View.INVISIBLE);
                break;*/
            case R.id.iv_cancel:
                ivTrash.setVisibility(View.VISIBLE);
                ivEdit.setVisibility(View.VISIBLE);
                ivSave1.setVisibility(View.INVISIBLE);
                ivCancel.setVisibility(View.INVISIBLE);
                adapter.updateData(0);
                break;
            case R.id.tv_cancel:
                mPopupWindow.dismiss();
                break;
            case R.id.tv_photograph:
                checkStoragePermission();
                break;
            case R.id.tv_fromAlbum:
                checkReadPermission();
                break;
            case R.id.tv_doodling:
                mPopupWindow.dismiss();
                showDoodlingWindow();
                break;
            case R.id.tv_cancle:
                mDoodlingWindow.dismiss();
                showPopWindow();
                drawingBoardView.clean();
                break;
            case R.id.tv_complete:
                cropRawPhoto(getImageContentUri(drawingBoardView.save()));
                mDoodlingWindow.dismiss();
                break;
        }
    }

    private void postSave() {
        OkHttpClient okHttpClient  = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10,TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();

        EditSaveBean editSaveBean = new EditSaveBean();
        //{"Model":{"NoteID":"PN_2019012536a82f31-143f-4e49-b73d-3a566d0196df","QuesID":"CBBE07048DHE10000OW",
        //    "TypeNo":"E","GenreID":"3","QuesBrief":"Who is ill in hospital?","Title":"测试1221",
        // "Content":"大22撒大撒222210000228q8487924238923022112345","GlobalGrade":"K9",
        // "CourseClassID":"0A99D23C-A0F4-436F-9A8D-D6ECD382189E","ImagePath":""},
        // "SchoolID":"S22-sa-2963","SubjectID":"C","StuID":"sastu255","Flag":1}
        //使用Gson 添加 依赖 compile 'com.google.code.gson:gson:2.8.1'
        editSaveBean.setSchoolID("S22-sa-2963");
        editSaveBean.setSubjectID("C");
        editSaveBean.setStuID("sastu255");
        editSaveBean.setFlag(1);
        EditSaveBean.ModelBean bean = new EditSaveBean.ModelBean();
        bean.setNoteID("PN_2019012536a82f31-143f-4e49-b73d-3a566d0196df");
        bean.setQuesID("CBBE07048DHE10000OW");
        bean.setTypeNo("E");
        bean.setGenreID("3");
        bean.setQuesBrief("Who is ill in hospital?");
        bean.setTitle("测试1221");
        bean.setContent("大22撒大撒222210000228q8487924238923022112345");
        bean.setGlobalGrade("K9");
        bean.setCourseClassID("0A99D23C-A0F4-436F-9A8D-D6ECD382189E");
        String path = "";
        Log.i("tj_path",imagePathList.size()+"");
        if (imagePathList.size() == 1){
            path = imagePathList.get(0);
        }else if (imagePathList.size() > 1){
            for (int i = 0; i < imagePathList.size(); i++){
                path = path + imagePathList.get(i) + "|";
            }
            path = path.substring(0,path.length() - 1);
        }
        Log.i("tj_path",path+"111");
        bean.setImagePath(path);
        editSaveBean.setModel(bean);
        Gson gson = new Gson();
        //使用Gson将对象转换为json字符串
        String json = gson.toJson(editSaveBean);

        //MediaType  设置Content-Type 标头中包含的媒体类型值
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , json);

        Request request = new Request.Builder()
                .url("http://172.16.41.235:2019/api/ZNBK/W_ZNBK_SaveOrDeleteNote")//请求的url
                .post(requestBody)
                .build();

        //创建/Call
        Call call = okHttpClient.newCall(request);
        //加入队列 异步操作
        call.enqueue(new Callback() {
            //请求错误回调方法
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("连接失败");
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //System.out.println(response.body().string());
                Log.i("tj_reponse",response.body().string());
            }
        });
    }

    /*private void getImagePost(List<File> files) {
        for (File file :files){
            if (file.exists()){
                upLoad2Server(file);
            }
        }

    }*/

    private void upLoad2Server(File file) {
        OkHttpClient client = new OkHttpClient();
        // form 表单形式上传
        MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if(file != null){
            // MediaType.parse() 里面是上传的文件类型。
            RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
            String filename = file.getName();
            // 参数分别为， 请求key ，文件名称 ， RequestBody
            requestBody.addFormDataPart("file", filename, body);
        }
        Request request = new Request.Builder().url("http://172.16.41.235:2019/api/ZNBK/W_ZNBK_ImgUploadImage").post(requestBody.build()).build();
        // readTimeout("请求超时时间" , 时间单位);
        client.newBuilder().readTimeout(5000, TimeUnit.MILLISECONDS).build().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Log.i("tj_resopnse",string);
                Gson gson = new Gson();
                Type type = new TypeToken<List<ImagePostBean>>(){}.getType();
                final List<ImagePostBean> infoBeans = gson.fromJson(string,type);
                Message msg =Message.obtain();
                msg.obj = infoBeans.get(0);
                msg.what = 0;   //标志消息的标志
                handler.sendMessage(msg);
            }
        });

    }
    private void checkStoragePermission() {
        int result = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (result == PackageManager.PERMISSION_DENIED) {
            String[] permissions = {/*Manifest.permission.WRITE_EXTERNAL_STORAGE
                    ,*/Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE};
            ActivityCompat.requestPermissions(this, permissions, PERMISSION_READ_AND_CAMERA);
        } else {
            choseHeadImageFromCameraCapture();
        }
    }
    private void checkReadPermission() {
        int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        if (permission == PackageManager.PERMISSION_DENIED){
            String[] permissions ={Manifest.permission.READ_EXTERNAL_STORAGE};
            ActivityCompat.requestPermissions(this,permissions, PERMISSION_READ);
        }else {
            choseHeadImageFromGallery();
        }

    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode){
            case PERMISSION_READ_AND_CAMERA:
                for (int i=0;i<grantResults.length;i++){
                    if (grantResults[i] == PackageManager.PERMISSION_DENIED){
                        Toast.makeText(this, "why ??????", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                choseHeadImageFromCameraCapture();
                break;
            case PERMISSION_READ:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    choseHeadImageFromGallery();
                }
                break;
        }

    }

    // 从本地相册选取图片作为头像
    private void choseHeadImageFromGallery() {
        // 设置文件类型    （在华为手机中不能获取图片，要替换代码）
        /*Intent intentFromGallery = new Intent();
        intentFromGallery.setType("image*//*");
        intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intentFromGallery, CODE_GALLERY_REQUEST);*/

        Intent intentFromGallery = new Intent(Intent.ACTION_PICK, null);
        intentFromGallery.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intentFromGallery, CODE_GALLERY_REQUEST);

    }
    // 启动手机相机拍摄照片作为头像
    private void choseHeadImageFromCameraCapture() {
        String savePath = mExtStorDir;
        Intent intent = null;
        // 判断存储卡是否可以用，可用进行存储
        if (hasSdcard()) {
            //设定拍照存放到自己指定的目录,可以先建好
            File file = new File(savePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            Uri pictureUri;
            File pictureFile = new File(savePath, IMAGE_FILE_NAME);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                pictureUri = FileProvider.getUriForFile(this, getPackageName()+".fileProvider", pictureFile);
            } else {
                intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                pictureUri = Uri.fromFile(pictureFile);
            }
            if (intent != null) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT,
                        pictureUri);
                startActivityForResult(intent, CODE_CAMERA_REQUEST);
            }
        }
    }
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            // 有存储的SDCard
            return true;
        } else {
            return false;
        }
    }
    private void showPopWindow() {
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        } else {
            mPopupWindow.showAsDropDown(ivSave,  0,
                    -720);
            WindowManager.LayoutParams lp = this.getWindow()
                    .getAttributes();
            lp.alpha = 0.4f;
            this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            this.getWindow().setAttributes(lp);

        }
    }
    private void showDoodlingWindow(){
        if (mDoodlingWindow != null && mDoodlingWindow.isShowing()){
            mDoodlingWindow.dismiss();
        }else {
            mDoodlingWindow.showAsDropDown(ivSave);
            WindowManager.LayoutParams lp = this.getWindow()
                    .getAttributes();
            lp.alpha = 0.4f;
            this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            this.getWindow().setAttributes(lp);

        }
    }
}
